package com.xfcycle.zebrabikegp.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.Toast;

import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.constant.BluetoothDeviceConstant;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;

/**
 * 车辆低电量设置
 */
public class BsLowBatteryLevelFoldbackActivity extends RootActivity {

    private static final String TAG = "BsLowBatteryProtect";

    private ImageView iv_back;
    private Switch switch_state;
    private RelativeLayout rl_cover;

    private HandleDataByBLEUtil handleDataByBLEUtil;

    //记录按下之前低电量的状态
    private boolean isLbFoldback;
    private LbHandleDataFromBleReceiver lbHandleDataFromBleReceiver;

    //判断是手动改变 还是 代码改变
    private boolean isManualCheck = false;

    private int tag = 0;

    //等待回馈
    private Handler waitHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (View.VISIBLE == rl_cover.getVisibility()) {
                rl_cover.setVisibility(View.GONE);

                if (!isManualCheck) {
                    Toast.makeText(getApplicationContext(), ToastConstant.QUERY_FAILURE, Toast.LENGTH_SHORT).show();
                } else {
                    isManualCheck = false;
                    switch_state.setChecked(!isLbFoldback);
                    Toast.makeText(getApplicationContext(), ToastConstant.MODIFY_FAILURE, Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bs_low_battery_protect);

        initView();
        initViewListener();
        setViewContent();
    }

    @Override
    protected void onResume() {
        super.onResume();

        //注册广播
        lbHandleDataFromBleReceiver = new LbHandleDataFromBleReceiver();
        registBroadcastReceiverAtActivity(lbHandleDataFromBleReceiver, BluetoothDeviceConstant.GET_DATA_FROM_BLUETOOTH_BROADCAST_RECEIVER_ACTION);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //回收广播接收者
        unregisterReceiver(lbHandleDataFromBleReceiver);
    }

    /***********************************************************************************************/
    /**                                 初始化控件对象 监听 控件内容方法                             **/
    /***********************************************************************************************/

    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        switch_state = (Switch) findViewById(R.id.switch_state);
        rl_cover = (RelativeLayout) findViewById(R.id.rl_cover);

        handleDataByBLEUtil = HandleDataByBLEUtil.getInstance(this, -1);
    }

    private void initViewListener() {
        //回退事件监听
        iv_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        //监听是否手动改变
        switch_state.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        isManualCheck = true;
                        break;
                }
                return false;
            }
        });

        //开关低电量保护
        switch_state.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isLbFoldback = isChecked;

                if (!isManualCheck) {
                    return;
                }

                rl_cover.setVisibility(View.VISIBLE);

                if (isChecked) {
                    //打开低电量保护
                    sendInstruction("t|w,141,36", 1);
                    return;
                }
                //关闭低电量保护
                sendInstruction("t|w,141,33", 1);
            }
        });
    }

    private void setViewContent() {
        rl_cover.setVisibility(View.VISIBLE);

        tag = 0;

        //查询低电量保护状态
        sendInstruction("t|r,141", 0);
    }

    //发送指令给蓝牙
    private void sendInstruction(String instruction, int tag) {
        handleDataByBLEUtil.sendDataToDevice(instruction);

        //发送修改 延时指令
        waitHandle.sendEmptyMessageDelayed(tag, 15 * 1000);
    }

    /***********************************************************************************************/
    /**                                 自定义广播接收者类                                          **/
    /***********************************************************************************************/

    /**
     * 广播接收者类，负责接收从蓝牙发出的数据并对其进行处理
     */
    class LbHandleDataFromBleReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String result = intent.getStringExtra("result");

            Log.w(TAG, "onReceive: ------------- " + result);

            if (result.contains("t|w,141")) {
                SystemClock.sleep(500);

                if (result.contains("t|w,141,33")) {
                    handleDataByBLEUtil.sendDataToDevice("t|w,142,33");
                } else {
                    handleDataByBLEUtil.sendDataToDevice("t|w,142,34");
                }
                return;
            }

            if (result.contains("t|w,142")) {
                SystemClock.sleep(500);

                if (result.contains("t|w,142,33")) {
                    handleDataByBLEUtil.sendDataToDevice("t|w,145,1");
                } else {
                    handleDataByBLEUtil.sendDataToDevice("t|w,145,10");
                }
                return;
            }

            if (result.contains("t|w,145")) {
                SystemClock.sleep(500);

                if (result.contains("t|w,145,1")) {
                    handleDataByBLEUtil.sendDataToDevice("t|w,146,0");
                } else {
                    handleDataByBLEUtil.sendDataToDevice("t|w,146,2");
                }
                return;
            }

            if (result.contains("t|w,146")) {
                SystemClock.sleep(500);

                handleDataByBLEUtil.sendDataToDevice("t|w,511,32767");

                SystemClock.sleep(500);

                Toast.makeText(context.getApplicationContext(), ToastConstant.MODIFY_SUCCESS, Toast.LENGTH_SHORT).show();
                rl_cover.setVisibility(View.GONE);

                handleDataByBLEUtil.sendDataToDevice("t|r,511");
                return;
            }

            if (result.contains("t|r,511,4096")) {
                if (View.VISIBLE == rl_cover.getVisibility()) {
                    Toast.makeText(context.getApplicationContext(), ToastConstant.MODIFY_SUCCESS, Toast.LENGTH_SHORT).show();
                    rl_cover.setVisibility(View.GONE);
                }
                return;
            }


            if (result.contains("t|r,141")) {
                if (result.contains("141,33")) {
                    tag++;
                }

                SystemClock.sleep(500);
                handleDataByBLEUtil.sendDataToDevice("t|r,142");
                return;
            }

            if (result.contains("t|r,142")) {
                if (result.contains("142,33")) {
                    tag++;
                }

                SystemClock.sleep(500);
                handleDataByBLEUtil.sendDataToDevice("t|r,145");
                return;
            }

            if (result.contains("t|r,145")) {
                if (result.contains("145,1")) {
                    tag++;
                }

                SystemClock.sleep(500);
                handleDataByBLEUtil.sendDataToDevice("t|r,146");
                return;
            }

            if (result.contains("t|r,146")) {
                if (result.contains("146,0")) {
                    tag++;
                }

                if (tag < 4) {
                    isLbFoldback = true;
                }

                switch_state.setChecked(isLbFoldback);

                rl_cover.setVisibility(View.GONE);
                return;
            }
        }
    }
}
